package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service(version = "1.0.0")//声明版本号
public class RecommendUserApiImpl implements RecommendUserApi {


    @Autowired
    private MongoTemplate mongoTemplate;

    //查询一位得分最高的推荐用户
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        //查询一位最高得分推荐用户,按照得分倒序排
        Query query = Query.query(Criteria.where("toUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("score"))).limit(1);
        //查询Mongodb
        return this.mongoTemplate.findOne(query, RecommendUser.class);
    }


    //*查询全部，按照得分倒序
    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer pageNum, Integer pageSize) {
        //分页并且排序
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Order.desc("score")));
        //查询条件
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(pageRequest);
        //数据列表
        List<RecommendUser> recommendUsers = this.mongoTemplate.find(query, RecommendUser.class);
        //返回数据
        return new PageInfo<>(0, pageNum, pageSize, recommendUsers);
    }


    /**
     * 查询推荐好友的缘分值
     *
     * @param userId   好友的id
     * @param toUserId 我的id
     * @return
     */
    @Override
    public Double queryScore(Long userId, Long toUserId) {

        //查询好友id和推荐id
        Query query = Query.query(Criteria.where("userId").is(userId).
                and("toUserId").is(toUserId));

        RecommendUser recommendUser = this.mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser != null) {
            //拿到推荐分数
            return recommendUser.getScore();
        }
        return null;
    }
}
